﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SiemensOPC;
using Opc.Ua;
using Opc.Ua.Client;
using VswService_V7.Config;
using VswService_V7.DataBase.Tables;
using VswService_V7.Utility;
using System.Data;

namespace VswService_V7.OPC.DB
{
	public  class MustAddressDbData :SubscriptionDbDataBase
	{
		public MustAddressDbData(SimaticOPCClient opc, NodeConfig nodes) : base(opc, nodes)
		{

		}

		string _batchNo = "0";
		string _pipeNo = "0";

        string _Location = "MUST";

        /// <summary>
        /// 质量代码
        /// </summary>
		string _qualityCode = "0";
        string _qualityCode2 = "0";

        /// <summary>
        /// 标记qc 是否发生改变，如果不改变不需要记录
        /// </summary>
        bool _qualityCodeChanged = false;

        public override void CreateSubscription()
		{
            opcServer.QuickAddMonitorItem(opcNodes.MustAddress.GrpoupName, opcNodes.MustAddress.PublishTime, opcNodes.MustAddress.SampleTime,
                opcNodes.MustAddress.GetNodeAddress(), opcNodes.MustAddress.GetNodeDisplayName(),
                SubscriptionHandle);


            opcServer.QuickAddMonitorItem(opcNodes.MustPipeAddress.GrpoupName, opcNodes.MustPipeAddress.PublishTime, opcNodes.MustPipeAddress.SampleTime,
				opcNodes.MustPipeAddress.GetNodeAddress(), opcNodes.MustPipeAddress.GetNodeDisplayName(),
				SubscriptionHandlePipe);


        }

        private void SubscriptionHandle(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;
            if (monitoredItem.DisplayName == "Must_Ask")
            {
                bool ask;
                if (bool.TryParse(notification.Value.Value.ToString(), out ask))
                {
                    if (ask)
                    {
                        Console.WriteLine(_Location + " UPDATE REQ: " + notification.Value);
                        Task.Run(() => HandlePipe());
                    }
                    else
                    {
                        opcServer.WriteValue("false", opcNodes.MustAddress.Must_Rsp);
                    }
                }
            }
        }

        private void SubscriptionHandlePipe(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
            if (notification == null || notification.Value.Value == null)
                return;

            if (notification.Value.Value.ToString().Equals("0"))
                return;

            switch (monitoredItem.DisplayName)
            {
                case "Batch_No":
                    {
                        _batchNo = notification.Value.Value.ToString();
                        break;
                    }
                case "Pipe_No":
                    {
                        _pipeNo = notification.Value.Value.ToString();
                        break;
                    }
                case "Quality_Code":
                    {
                        _qualityCode = notification.Value.Value.ToString();
                        _qualityCodeChanged = true;
                        break;
                    }
                case "Quality_Code2":
                    {
                        _qualityCode2 = notification.Value.Value.ToString();
                        _qualityCodeChanged = true;
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }





        private async Task HandlePipe()
        {

            await Task.Delay(2000);
            if (_batchNo.Equals("0") || _pipeNo.Equals("0")|| !_qualityCodeChanged)
                return;
            //QC CODE 高低位交换
            Console.WriteLine(_Location + " handleqc start record");

            int pipeNum = int.Parse(_pipeNo.ToString());
            string pipeNo = _batchNo + pipeNum.ToString("000");

            try
            {
                PIPE_INFO.UpdatePipeInfoMustRecord(pipeNo, DateTime.Now, _qualityCode, _qualityCode2, _Location);
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("HandlePipe", ex);
            } 
            _qualityCodeChanged = false;
            opcServer.WriteValue("true", opcNodes.MustAddress.Must_Rsp);
            Console.WriteLine(_Location + " qc changed: " + pipeNum);
     
        }
	}
}
